package com.zsh.service.impl;

import com.zsh.dao.BookDao;
import com.zsh.dao.OrderDao;
import com.zsh.dao.OrderItemDao;
import com.zsh.dao.impl.BookDaoImpl;
import com.zsh.dao.impl.OrderDaoImpl;
import com.zsh.dao.impl.OrderItemDaoImpl;
import com.zsh.pojo.*;
import com.zsh.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    @Override
    public String createOrder(Cart cart, Integer userId) {
        //订单号
        String orderId = System.currentTimeMillis() + "" + userId;

        Order order = new Order(orderId,new Date(),cart.getTotalPrice(),0,userId);

        orderDao.saveOrder(order);

//        int i = 12/0;

        //遍历购物车的商品项，转为订单项
        for (Map.Entry<Integer, CartItem> entry: cart.getItems().entrySet()){
            CartItem cartItem = entry.getValue();

            OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId);

            //更新库存和销量
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDao.updateBook(book);

            orderItemDao.saveOrderItem(orderItem);

        }
        //清空购物车
        cart.clear();

        return orderId;
    }

    @Override
    public List<Order> showMyOrders(Integer userId) {
        return orderDao.queryOrderByUserId(userId);
    }

    @Override
    public List<OrderItem> showOrderDetail(String orderId) {
        return orderItemDao.queryOrderItemsByOrderId(orderId);
    }
}
